//
//  JLCFHTTPResponseSerializer.m
//  QTZ
//
//  Created by ski on 2017/7/6.
//  Copyright © 2017年 ski. All rights reserved.
//

#import "JLCFHTTPResponseSerializer.h"

static NSError * QTZErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
    if (!error) {
        return underlyingError;
    }
    
    if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
        return error;
    }
    
    NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
    mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
    
    return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
}

static BOOL QTZErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
    if ([error.domain isEqualToString:domain] && error.code == code) {
        return YES;
    } else if (error.userInfo[NSUnderlyingErrorKey]) {
        return QTZErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
    }
    
    return NO;
}

@implementation JLCFHTTPResponseSerializer

+ (instancetype)serializer
{
    JLCFHTTPResponseSerializer *serializer = [[self alloc] init];
    return serializer;
}

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/plain", nil];
    
    return self;
}

- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error
{
    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
        if (!error || QTZErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
            return nil;
        }
    }
    
    if (!data) {
        return nil;
    }
    
    id responseObject = nil;
    NSError *serializationError = nil;
    
    //    //messagepack
    //    if ([response.MIMEType isEqualToString:ContentType_MessagePack]) {
    //        responseObject = [MPMessagePackReader readData:data error:&serializationError];
    //    }
    //    //json
    //    else
    //    {
    //        responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&serializationError];
    //    }
    
    responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&serializationError];
    
    if (error) {
        *error = QTZErrorWithUnderlyingError(serializationError, *error);;
    }
    
    return responseObject;
}

@end
